package com.ybwh.springboot2.minio;

import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Component
@Slf4j
public class MinioService implements InitializingBean {

    @Autowired
    private MinioConfig minioConfig;

    @Resource
    private MinioClient minioClient;


    @Override
    public void afterPropertiesSet() throws Exception {
        /**
         * 使用bucket必须是当前appKey创建的
         *
         */
        if (!bucketExists(minioConfig.getBucket())) {
            try {
                makeBucket(minioConfig.getBucket());
            }catch (Exception e){
                log.error("",e);
            }
        }
    }

    /**
     * 查看存储bucket是否存在
     *
     * @return boolean
     */
    public boolean bucketExists(String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    }

    /**
     * 创建存储bucket
     */
    public void makeBucket(String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        minioClient.makeBucket(MakeBucketArgs.builder()
                .bucket(bucketName)
                .build());

    }

    /**
     * 删除存储bucket
     *
     * @return Boolean
     */
    public void removeBucket(String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        minioClient.removeBucket(RemoveBucketArgs.builder()
                .bucket(bucketName)
                .build());

    }

    /**
     * 获取全部bucket
     */
    public List<Bucket> getAllBuckets() throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        return minioClient.listBuckets();
    }


    /**
     * 文件上传
     *
     * @param file 上传的文件
     * @param objectName 存储在minio的对象名
     * @return
     */
    public String upload(MultipartFile file,String objectName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            throw new RuntimeException();
        }
        PutObjectArgs objectArgs = PutObjectArgs.builder()
                .bucket(minioConfig.getBucket())
                .object(objectName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        minioClient.putObject(objectArgs);

        return objectName;
    }


    /**
     * 文件上传
     *
     * @param file 上传的文件
     * @return
     */
    public String upload(File file, String contentType,String objectName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String originalFilename = file.getName();
        if (StringUtils.isBlank(originalFilename)) {
            throw new RuntimeException();
        }

        PutObjectArgs objectArgs = PutObjectArgs.builder()
                .bucket(minioConfig.getBucket())
                .object(objectName)
                .stream(new FileInputStream(file), file.length(), -1)
                .contentType(contentType)
                .build();
        minioClient.putObject(objectArgs);

        return objectName;
    }

    /**
     * 预览图片
     *
     * @param fileName 文件名称
     * @return 图片地址
     */
    public String preview(String fileName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        // 查看文件地址
        GetPresignedObjectUrlArgs build = GetPresignedObjectUrlArgs.builder()
                .bucket(minioConfig.getBucket())
                .object(fileName)
                .method(Method.GET)
                .build();
        return minioClient.getPresignedObjectUrl(build);

    }

    /**
     * 文件下载
     *
     * @param fileName 文件名称
     * @param res      response
     */
    public void download(String fileName, HttpServletResponse res) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(minioConfig.getBucket())
                .object(fileName).build();
        GetObjectResponse object = minioClient.getObject(objectArgs);
        IOUtils.copy(object, res.getOutputStream());
    }


    public void download(String fileName, OutputStream outputStream) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(minioConfig.getBucket())
                .object(fileName).build();
        GetObjectResponse response = minioClient.getObject(objectArgs);
        IOUtils.copy(response, outputStream);
    }

    /**
     * 查看文件对象
     *
     * @return 存储bucket内文件对象信息
     */
    public List<Item> listObjects(String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        if (StringUtils.isBlank(bucketName) || !bucketExists(bucketName)) {
            return null;
        }
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(bucketName).build());
        List<Item> items = new ArrayList<>();
        for (Result<Item> result : results) {
            items.add(result.get());
        }

        return items;
    }


    /**
     * 获取单个桶中的所有文件对象名称
     *
     * @param bucket 桶名称
     * @return {@link List}<{@link String}>
     */
    public List<String> getBucketObjectName(String bucket) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        boolean exsit = bucketExists(bucket);
        if (exsit) {
            List<String> listObjetcName = new ArrayList<>();
            Iterable<Result<Item>> myObjects = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucket).build());
            for (Result<Item> result : myObjects) {
                Item item = result.get();
                listObjetcName.add(item.objectName());
            }
            return listObjetcName;

        }
        return null;
    }

    /**
     * 删除
     *
     * @param fileName 文件名称
     */
    public void remove(String fileName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(minioConfig.getBucket()).object(fileName).build());

    }

    /**
     * 批量删除文件
     *
     * @param bucket      桶名称
     * @param objectNames 对象名称
     * @return boolean
     */
    public boolean removeObjects(String bucket, List<String> objectNames) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        boolean exsit = bucketExists(bucket);
        if (exsit) {
            List<DeleteObject> objects = new LinkedList<>();
            for (String str : objectNames) {
                objects.add(new DeleteObject(str));
            }
            minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucket).objects(objects).build());
            return true;

        }
        return false;
    }

}